package com.learn.demo.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

public class HttpServerHandlerDemo extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if(msg instanceof HttpRequest){
            HttpRequest httpRequest = (HttpRequest) msg;
            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("client request for favicon.ico, no response");
                return;
            }
            System.out.println("pipeline hashCode is " + ctx.channel().pipeline().hashCode());
            System.out.println("msg type is " + msg.getClass());
            System.out.println("client address is " + ctx.channel().remoteAddress());
            //回复信息
            ByteBuf responsTxt = Unpooled.copiedBuffer("Hello Netty Http Server", CharsetUtil.UTF_8);
            FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, responsTxt);
            //设置头信息
            httpResponse
                    .headers()
                    .set(HttpHeaderNames.CONTENT_TYPE, "text/Plain")
                    .set(HttpHeaderNames.CONTENT_LENGTH, responsTxt.readableBytes());
            //返回信息
            ctx.writeAndFlush(httpResponse);
        }
    }
}
